package com.hmo.appshop.mamager.dto.commom;

import com.hmo.appshop.mamager.custom.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.FileSystemUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

@Component
public class MyFileUtils {

    @Value("${apk}")
    private String apk;
    @Value("${image}")
    private String image;

    public File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {

        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除本地临时文件
     * @param file
     */
    public void delteTempFile(File file) {
        if (file != null) {
            File del = new File(file.toURI());
            del.delete();
        }
    }

    //  拷贝apk icon
    public String openApkSaveIcon(String iconName,File apk) throws IOException {
        ZipInputStream zin = null;
        //new一个文件对象用来保存图片，默认保存当前工程根目录
        File imageFile = new File(image +System.currentTimeMillis()+".png");
        InputStream in = null;
        ZipFile zf = null;
        ByteArrayOutputStream outStream = null;
        FileOutputStream fileOutStream = null;
        try {
            //  访问apk 里面的文件
            zf = new ZipFile(apk);
            in = new BufferedInputStream(new FileInputStream(apk));
            zin = new ZipInputStream(in);
            ZipEntry ze;
            while ((ze = zin.getNextEntry()) != null) {
                if (ze.getName().equals(iconName)) {
                    //  拷贝出图标

                    InputStream inStream = zf.getInputStream(ze);

                    outStream = new ByteArrayOutputStream();
                    //创建一个Buffer字符串
                    byte[] buffer = new byte[1024];
                    //每次读取的字符串长度，如果为-1，代表全部读取完毕
                    int len = 0;
                    //使用一个输入流从buffer里把数据读取出来
                    while ((len = inStream.read(buffer)) != -1) {
                        //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                        outStream.write(buffer, 0, len);
                    }
                    //关闭输入流
                    inStream.close();
                    //把outStream里的数据写入内存

                    //得到图片的二进制数据，以二进制封装得到数据，具有通用性
                    byte[] data = outStream.toByteArray();
                    //创建输出流
                    fileOutStream = new FileOutputStream(imageFile);
                    //写入数据
                    fileOutStream.write(data);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            fileOutStream.close();
            outStream.close();
            zin.closeEntry();
            in.close();
            zf.close();
        }
        return imageFile.getName();
    }

    //保存file
    public File saveFile(int iconPicturApk,MultipartFile multipartFile){
        String filename = multipartFile.getOriginalFilename();//获取文件名称
        String suffixname = filename.substring(filename.lastIndexOf("."));//后缀
        long l = System.currentTimeMillis();
        String fileName=l+suffixname;
        File file = new File(image);
        if (iconPicturApk==3) {
            file=new File(apk);
        }
        File apkFile;
        try {
            apkFile = new File(file.getAbsolutePath()+"/"+fileName);

            multipartFile.transferTo(apkFile);
        } catch (IOException e) {
            throw new ServiceException(500,"文件保存到服务器异常");
        }
        return apkFile;
    }

    //删除文件
    public void delFile(int iconPicturApk,String fileName){
        if (fileName==null){
            return;
        }
        String filePath=apk+fileName;
        if (iconPicturApk==1 || iconPicturApk==2)
            filePath= image +fileName;

        FileSystemUtils.deleteRecursively(new File(filePath));
    }

}
